﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Areas.PropertyManage.Controllers
{

    public class CS_DecorateController : MvcControllerBase
    {
        private DecorateBLL bll = new DecorateBLL();

        #region 视图

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Index()
        {
            ViewBag.Type = new DataItemDetailBLL().GetEntity("ItemName", "装修巡检", "ItemId", "PollingType").ItemDetailId;
            var AuditSetting = new SettingBLL().GetWorkAuditEntityByCode(((int)CodeRuleEnum.DecorateCode).ToString());
            ViewBag.AuditSetting = AuditSetting == null ? "" : AuditSetting.Id;
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Form()
        {
            ViewBag.Mode = new CodeRuleBLL().CheckBillCodeMode(((int)CodeRuleEnum.DecorateCode).ToString());
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult DecForm()
        {
            return View();
        }
        #endregion


        #region 查询数据


        #region 查询单据状态树
        private List<TreeStatusEntity> GetList()
        {
            DataTable dt = bll.GetCountList();
            List<TreeStatusEntity> li = new List<TreeStatusEntity>();
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName == "all")
                        li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(StateEnum.All), StateEnum.All.ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "unsubmit")
                        li.Add(new TreeStatusEntity(StateEnum.All.ToString(), EnumAttribute.GetDescription(StateEnum.UnSubmit), ((int)StateEnum.UnSubmit).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "approving")
                        li.Add(new TreeStatusEntity(StateEnum.All.ToString(), EnumAttribute.GetDescription(StateEnum.Approving), ((int)StateEnum.Approving).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "decorating")
                        li.Add(new TreeStatusEntity(StateEnum.All.ToString(), EnumAttribute.GetDescription(StateEnum.Decorating), ((int)StateEnum.Decorating).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "unprojectinspection")
                        li.Add(new TreeStatusEntity(((int)StateEnum.Decorating).ToString(), EnumAttribute.GetDescription(StateEnum.UnProjectInspection), ((int)StateEnum.UnProjectInspection).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "projectinspecting")
                        li.Add(new TreeStatusEntity(((int)StateEnum.Decorating).ToString(), EnumAttribute.GetDescription(StateEnum.ProjectInspecting), ((int)StateEnum.ProjectInspecting).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "projectinspected")
                        li.Add(new TreeStatusEntity(((int)StateEnum.Decorating).ToString(), EnumAttribute.GetDescription(StateEnum.ProjectInspected), ((int)StateEnum.ProjectInspected).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "decorated")
                        li.Add(new TreeStatusEntity(StateEnum.All.ToString(), EnumAttribute.GetDescription(StateEnum.Decorated), ((int)StateEnum.Decorated).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "unwholeinspection")
                        li.Add(new TreeStatusEntity(((int)StateEnum.Decorated).ToString(), EnumAttribute.GetDescription(StateEnum.UnWholeInspection), ((int)StateEnum.UnWholeInspection).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "unwholeinspecting")
                        li.Add(new TreeStatusEntity(((int)StateEnum.Decorated).ToString(), EnumAttribute.GetDescription(StateEnum.WholeInspecting), ((int)StateEnum.WholeInspecting).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "wholeinspected")
                        li.Add(new TreeStatusEntity(((int)StateEnum.Decorated).ToString(), EnumAttribute.GetDescription(StateEnum.WholeInspected), ((int)StateEnum.WholeInspected).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "unsecondinspection")
                        li.Add(new TreeStatusEntity(((int)StateEnum.WholeInspected).ToString(), EnumAttribute.GetDescription(StateEnum.UnSecondInspection), ((int)StateEnum.UnSecondInspection).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "secondinspection")
                        li.Add(new TreeStatusEntity(((int)StateEnum.WholeInspected).ToString(), EnumAttribute.GetDescription(StateEnum.SecondInspection), ((int)StateEnum.SecondInspection).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "secondinspected")
                        li.Add(new TreeStatusEntity(((int)StateEnum.WholeInspected).ToString(), EnumAttribute.GetDescription(StateEnum.SecondInspected), ((int)StateEnum.SecondInspected).ToString(), dt.Rows[0][i].ToInt()));
                    else
                        continue;
                }
            }
            return li;
        }
        /// <summary>
        /// 状态树
        /// </summary>
        /// <returns></returns>
        public ActionResult GetStateTreeList()
        {
            var data = GetList();
            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (TreeStatusEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.PValue == item.Value) == 0 ? false : true;
                tree.id = item.Value;
                tree.text = item.Text + "<" + item.Count + ">";
                tree.value = item.Value;
                if (item.PValue == "0") tree.isexpand = true;
                else tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.PValue;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        #endregion
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pagination">分页条件</param>
        /// <param name="queryJson">查询条件</param>
        /// <returns></returns> 
        public ActionResult GetPageListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var data = bll.GetPageList(pagination, queryJson);
            var psruct = new PStructCache().GetList();
            foreach (var item in data)
            {
                item.PStructId = psruct.Count(t => t.Id == item.PStructId) > 0 ? psruct.FirstOrDefault(t => t.Id == item.PStructId).Name : "";
            }
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }


        /// <summary>
        /// 装修单单据列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetTreeJson()
        {
            var data = bll.GetList(-1, "").Where(t => t.State == 3).ToList();
            var treeList = new List<TreeEntity>();
            foreach (DecorateBillEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                tree.id = item.Id;
                tree.text = item.Code;
                tree.value = item.PStructId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = false;
                tree.parentId = "0";
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public ActionResult GetFormBillJson(string keyValue)
        {
            var obj1 = bll.GetEntity(keyValue);
            var obj2 = new DecorateDetailBLL().GetEntity(keyValue);
            var PStruct = new PStructBLL().GetEntity(obj1.PStructId);
            var jsonData = new
            {
                data = obj1,
                data2 = obj2,
                PStructName = PStruct != null ? PStruct.Name : ""
            };
            return Content(jsonData.ToJson());
        }








        /// <summary>
        /// 查询工单默认巡检项目
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public ActionResult GetPollingResultItem(string keyValue)
        {
            //var relationdata = new PollingRelationOIBLL().GetList().Where(t => t.ObjectId == keyValue && t.TypeId == "9b5a3e03-499b-4003-9b11-9558191d7b2c").ToList();
            var Itemdata = new PollingBLL().GetItemList("", "", "9b5a3e03-499b-4003-9b11-9558191d7b2c").ToList();
            var resultItem = new PollingResultBLL().GetList().Where(t => t.ObjectId == keyValue && t.Bcode == "9b5a3e03-499b-4003-9b11-9558191d7b2c");
            var newResult = from c in
                                (from a in Itemdata join b in resultItem on a.Id equals b.Icode select new { ItemId = a.Id, ItemCode = a.Code, a.Name, a.Frenquency, a.Unit, a.UnitNum, ResultId = b.Id, b.Icode, b.ObjectId, b.Bcode })
                            group c by new { c.ObjectId, c.Icode } into d
                            select new
                            {
                                ItemName = d.Select(p => p.Name),
                                ItemCode = d.Select(p => p.ItemCode),
                                Frenquency = d.Select(p => p.Frenquency),
                                Unit = d.Select(p => p.Unit),
                                UnitNum = d.Select(p => p.UnitNum),
                                ResultId = d.Select(p => p.ResultId),
                                TypeId = d.Select(p => p.Bcode),
                                ObjectId = d.Select(p => p.ObjectId),
                                ItemId = d.Select(p => p.ItemId),
                                Count = d.Count()
                            };

            return Content(newResult.ToJson());
        }
        public ActionResult GetPollingReaultDetail(string ResultId, string itemId)
        {
            var datareultdetail = new PollingResultBLL().GetDetailList().Where(t => t.PollingResultId == ResultId);
            var dataContent = new PollingBLL().GetContentList();//.Where(t => t.ICode == itemId);
            var data = from a in datareultdetail join b in dataContent on a.ContentId equals b.Id select new { b.Id, b.Name, b.Type, b.Criterion, b.CheckWay, b.TypeDescription, a.Text, a.Value, a.IsException, a.Memo, a.CreateDate, a.CreateUserName };
            return Content(data.ToJson());
        }
        /// <summary>
        /// 查询整改记录
        /// </summary>
        /// <param name="SourceId"></param>
        /// <param name="State"></param>
        /// <returns></returns>
        public ActionResult GetAbarbeitungList(string SourceId)
        {
            var data = new RectificationBillBLL().GetList(SourceId);
            return Content(data.ToJson());
        }


        /// <summary>
        /// 查询审批数据
        /// </summary>
        /// <param name="BillId"></param>
        /// <returns></returns>
        public ActionResult GetAuditList(string BillId)
        {
            var data = new AuditRecordBLL().GetList(BillId);
            return Content(data.ToJson());
        }






        #endregion

        #region 提交数据
        /// <summary>
        /// 保存装修单
        /// </summary> 
        /// <param name="KeyValue">装修单key</param>
        /// <param name="BaseInfo">基础信息</param>
        /// <param name="fileInfo">资料信息</param>
        /// <param name="ProjectInfo">审批信息</param>
        /// <param name="InspectionInfo">巡检信息</param>
        /// <param name="AbarbeitungInfo">整改信息</param>
        /// <param name="AcceptanceInfo">验收信息</param>
        /// <returns></returns>
        public ActionResult SaveForm(string keyValue, int Type, string BaseInfo, string fileInfo)
        {
            try
            {
                DecorateBillEntity bill = BaseInfo.ToObject<DecorateBillEntity>();
                DecorateBillDetailEntity detail = new DecorateDetailBLL().GetEntity(keyValue);
                List<MaterialSeedEntity> list = fileInfo.ToList<MaterialSeedEntity>();
                bll.SaveForm(keyValue, Type, bill, detail, list);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }

        public ActionResult Decoratefinish(string keyValue)
        {
            try
            {
                bll.Decoratefinish(keyValue);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

        public ActionResult RemoveForm(string keyValue)
        {
            try
            {
                bll.RemoveForm(keyValue);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }

        public ActionResult SaveAuditForm(AuditRecordEntity AudtiEntity)
        {
            try
            {
                new AuditRecordBLL().SaveForm(1, AudtiEntity, true);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }
        #endregion









    }
}
